import React, { useState, useEffect, createContext, useContext, useRef } from 'react'

// export const pane =  () => {}
// export default () => {}

// useState/useEffect
export function CountPane() {
  const [count, setCount] = useState(0)

  // useEffect: componentDidMount，componentDidUpdate 和 componentWillUnmount 这三个函数的组合
  // 第二个参数处理componentDidUpdate，可选：例如[],当count发生变化是不打印count;
  // 第二个参数处理componentDidUpdate，可选：例如[count],当count发生变化是打印count;
  useEffect(() => {
    console.log("count", count)
    // return () => {
    //   console.log("类似componentWillUnmount，当组件即将被移出时执行")
    // }
  }, [count])

  function subCount() {
    setCount(count - 1)
  }
  return (
    <>
      <div>count:{count}</div>
      <button onClick={() => { setCount(count + 1) }}>加1</button>
      <button onClick={subCount}>减1</button>
    </>
  )
}

// useContext
// 如果父子组件不在同一个文件里，可以: export const NameContext = createContext(),然后子组件import导入
const NameContext = createContext()
export function ContextPane() {
  const [name, setName] = useState("burc")
  return (
    <NameContext.Provider value={{ name, setName }}>
      <ContextChildPane />
    </NameContext.Provider>
  )
}

function ContextChildPane() {
  const { name, setName } = useContext(NameContext);
  return (
    <div>
      <div>name:{name}</div>
      <button onClick={() => setName(name + 'A')}>改变name</button>
    </div>
  )
}


// useRef
export function RefPane() {
  const myRef = useRef()
  useEffect(() => {
    myRef.current.value = '初始值'
  }, [])
  function onClickInput() {
    myRef.current.focus()
  }
  return (
    <div>
      <input ref={myRef}></input><br></br>
      <button onClick={onClickInput}>聚焦</button>
    </div>
  )
}